import type { Directive, DirectiveBinding } from 'vue'
import router from '@/router'
import { usePermissionStoreWithOut } from '@/store/modules/permission'
const permissionStore = usePermissionStoreWithOut()

/**
 * @description {Directive} 字符权限(按钮权限)
 * @binding {string[]} 传入字符权限标识组，例如：v-hasPermi="['add','edit']"
 * @author 花东红
 * @time 2023/12/22
 */
const hasPermi: Directive = {
  mounted(el: HTMLElement, binding: DirectiveBinding, VNode: any): void {
    const roleRouterList = permissionStore.$state.addRouters
    // const permission = (router.currentRoute.value.meta.permission || []) as string[]
    // 遍历 roleRouterList 里的 item.children，收集所有 el.meta.permission 组成一个数组
    const permission: string[] = []
    roleRouterList.forEach((item) => {
      if (Array.isArray(item.children)) {
        item.children.forEach((child) => {
          if (child.meta && Array.isArray(child.meta.permission)) {
            permission.push(...child.meta.permission)
          }
        })
      }
    })
    console.log(permission, 'permission')
    const { value } = binding
    if (value instanceof Array && value.length) {
      const includeAuth = permission.some((v: string) => value.includes(v))
      if (!includeAuth) el.parentNode && el.parentNode.removeChild(el)
    }
  }
}

export default hasPermi
